package com.hp.attendance.util;

import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class DBUtil {
    private static DataSource dataSource;
    static {
        try {
            Properties p = new Properties();
            p.load(DBUtil.class.getResourceAsStream("/jdbc.properties"));
//            p.load(new FileInputStream("jdbc_day04//jdbc.properties"));
            DruidDataSource ds = new DruidDataSource();
            ds.configFromPropety(p);
            dataSource=ds;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 获取连接
    public static Connection getConn() throws SQLException {
        Connection conn = dataSource.getConnection();
        return conn;
    }

    //释放资源
    public static void close(ResultSet rs , Statement st, Connection conn) throws SQLException {
        if(rs!=null){
            rs.close();
        }
        if(st!=null){
            st.close();
        }
        if(conn!=null){
            conn.close();
        }
    }


    public static void main(String[] args) throws SQLException {
        Connection conn = DBUtil.getConn();
        PreparedStatement ps = conn.prepareStatement("select * from hp_user");
        ResultSet rs = ps.executeQuery();
        while (rs.next()){
            int id = rs.getInt("id");
            String username = rs.getString("username");
            String password = rs.getString("password");
            String birthday = rs.getString("birthday");
            String address = rs.getString("address");
            System.out.println(id+","+username+","+password+","+birthday+","+address);
        }
    }
}
